﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;
using CLEX.AdminUI.Service;

namespace CLEX.AdminUI.ViewModel
{
    internal sealed class FriendRequestCreateVM : ViewModelBase
    {
        private readonly Facade facade;
        private RelayCommand create;
        private RelayCommand cancel;
        private FriendRequestData friendRequest = new FriendRequestData();
        private readonly List<UserReadVM> users;

        public ICommand Create
        {
            get
            {
                if (create == null)
                {
                    create = new RelayCommand(DoCreate);
                }
                return create;
            }
        }

        public ICommand Cancel
        {
            get
            {
                if (cancel == null)
                {
                    cancel = new RelayCommand(DoCancel);
                } 
                return cancel;
            }
        }

        public int FromUserId
        {
            get { return friendRequest.FromUserId; }
            set
            {
                if (friendRequest.FromUserId != value)
                {
                    friendRequest.FromUserId = value;
                    FirePropertyChanged("FromUserId");
                }
            }
        }

        public int ToUserId
        {
            get { return friendRequest.ToUserId; }
            set
            {
                if (friendRequest.ToUserId != value)
                {
                    friendRequest.ToUserId = value;
                    FirePropertyChanged("ToUserId");
                }
            }
        }

        public IEnumerable<UserReadVM> Users
        {
            get { return users; }
        } 

        public FriendRequestCreateVM(Facade facade)
        {
            this.facade = facade;
            this.users = facade.GetAllUsers().Select(p => new UserReadVM(p)).ToList();
        }

        private void DoCreate()
        {
            try
            {
                facade.CreateFriendRequest(friendRequest);
            }
            catch (Exception ex)
            {
                facade.ShowError("An unexpected error occured while creating the friend request.", ex);
                return;
            }
            FireCloseRequested();
        }

        private void DoCancel()
        {
            FireCloseRequested();
        }
    }
}
